package nl.hanze.designpatterns.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;

public class Executor {
	
	private String dbName;
	private String driver;
	private String userName;
	private String password;
	private String url;
	
		private static Executor instance = new Executor();
			   
	   //Connection
	   private Connection conn;
	   
	   /* A private Constructor prevents any other 
	    * class from instantiating (Singleton)
	    */
	   private Executor(){ 
		   conn = null;
		   url="jdbc:mysql://localhost:3306/";
		   driver="com.mysql.jdbc.Driver";
		   dbName="designpatterns";
		   userName="root";
		   password="";
		   try {
			Class.forName(driver).newInstance();
			conn = DriverManager.getConnection(url+dbName, userName, password);
		} catch (InstantiationException | IllegalAccessException
				| ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		    
		   System.out.println("Executor: Connected to database");
	   }
	   
	   /* Static 'instance' method, returns instance of Executor */
	   public static Executor getInstance() {
		   return instance;
	   }
	   
	public void executeQuery(String query){
		
		try {
			Statement stmt = conn.createStatement();
			stmt.executeUpdate(query);
			System.out.println("Executor: Sent query: " + query);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public <T> Iterator<T> getIterator(String query, Class<T> c){
		try{
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(query);
			System.out.println("Executor: Sent query: " + query);
			Iterator <T> iterator = new RowIterator <T>(rs, c);
			return iterator;
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
		
}
